package com.ruoyi.oar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.oar.domain.OarVerifiTask;
import com.ruoyi.oar.domain.dto.*;
import com.ruoyi.oar.domain.query.OarImpNetHouseQuery;
import com.ruoyi.oar.domain.query.OarVerifiTaskQuery;
import com.ruoyi.oar.mapper.OarVerifiTaskMapper;
import com.ruoyi.oar.service.OarHouseService;
import com.ruoyi.oar.service.OarImpNetHouseService;
import com.ruoyi.oar.service.OarTaskImpService;
import com.ruoyi.oar.service.OarVerifiTaskService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 核查任务Service业务层处理
 *
 * @author oar
 * @date 2022-02-26
 */
@Service
public class OarVerifiTaskServiceImpl implements OarVerifiTaskService {
    @Autowired
    private OarVerifiTaskMapper oarVerifiTaskMapper;
    @Autowired
    private OarImpNetHouseService oarImpNetHouseService;
    @Autowired
    private OarTaskImpService oarTaskImpService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private OarHouseService oarHouseService;
    /**
     * 线程service
     */
    @Autowired
    private  ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private ISysDeptService sysDeptService;


    /**
     * 查询核查任务
     *
     * @param id 核查任务主键
     * @return 核查任务
     */
    @Override
    public Optional<OarVerifiTaskDTO> selectOarVerifiTaskById(String id) {
//        List<OarImpNetHouseDTO> oarImpNetHouseList =oarImpNetHouseService.selectOarImpNetHouseByTaskId(id);
        return oarVerifiTaskMapper.selectOarVerifiTaskById(id).map(this::toDto);
    }

    /**
     * 查询核查任务列表
     *
     * @param oarVerifiTaskQuery 核查任务
     * @return 核查任务
     */
    @Override
    public List<OarVerifiTaskDTO> selectOarVerifiTaskList(OarVerifiTaskQuery oarVerifiTaskQuery) {
        return oarVerifiTaskMapper.selectOarVerifiTaskList(oarVerifiTaskQuery).stream().map(this::toDto).collect(Collectors.toList());
    }

    /**
     * 分页查询核查任务列表
     *
     * @param oarVerifiTaskQuery 核查任务
     * @return
     */
    @Override
    public TableDataInfo<OarVerifiTaskDTO> findAll(OarVerifiTaskQuery oarVerifiTaskQuery) {
        List<OarVerifiTask> list = oarVerifiTaskMapper.selectOarVerifiTaskList(oarVerifiTaskQuery);
        List<OarVerifiTaskDTO> dtoList = list.stream().map(this::toDto).collect(Collectors.toList());
        return PageUtil.getDataTable(dtoList, new PageInfo(list).getTotal());
    }

    /**
     * 新增核查任务
     *
     * @param oarVerifiTaskDTO 核查任务
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOarVerifiTask(OarVerifiTaskDTO oarVerifiTaskDTO) {
        checkOarVerifiTask(oarVerifiTaskDTO);
        OarImpNetHouseQuery oarImpNetHouseQuery = new OarImpNetHouseQuery();
        //oarImpNetHouseQuery.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        oarImpNetHouseQuery.setIsIssuedCheck(false);
        oarImpNetHouseQuery.setIsCheck(true);
        List<OarImpNetHouseDTO> list = oarImpNetHouseService.selectOarImpNetHouseList(oarImpNetHouseQuery);
        if (list == null || list.size() == 0) {
            throw new ServiceException("已选数据不能为空");
        }
        //oarVerifiTaskDTO.setId(SnowflakeWorker.nextId());
        List<OarTaskImpDTO> qarTaskImplist = new ArrayList();
        list.forEach(oarImpNetHouseDTO -> {
            OarTaskImpDTO qarTaskImpDTO = new OarTaskImpDTO();
            qarTaskImpDTO.setImpNetAboutId(oarImpNetHouseDTO.getId());
            qarTaskImpDTO.setTaskId(oarVerifiTaskDTO.getId());
            qarTaskImplist.add(qarTaskImpDTO);
        });
        //更新imphouse表状态为已下发
        OarImpNetHouseDTO oarImpNetHouseDTO = new OarImpNetHouseDTO();
        //oarImpNetHouseDTO.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        oarImpNetHouseDTO.setIsCheck(true);
        oarImpNetHouseDTO.setIsIssuedCheck(true);
        oarImpNetHouseService.updateisIssuedCheckByCreateBy(oarImpNetHouseDTO);
        //添加任务及中间表记录
        qarTaskImplist.forEach(qarTaskImp -> {
            oarTaskImpService.insertOarTaskImp(qarTaskImp);
        });
//        oarTaskImpService.batchImpTaskImp(qarTaskImplist);
        //插入一条任务记录
        oarVerifiTaskDTO.setVerifiNo("XM-WYFHC-" + DateUtils.dateTimeNow()+ToolUtil.getRandomString(3));
        oarVerifiTaskDTO.setTaskState(0);
        return oarVerifiTaskMapper.insertOarVerifiTask(toEntity(oarVerifiTaskDTO));
    }

    /**
     * 修改核查任务
     *
     * @param oarVerifiTaskDTO 核查任务
     * @return 结果
     */
    @Override
    public int updateOarVerifiTask(OarVerifiTaskDTO oarVerifiTaskDTO) {
        checkOarVerifiTask(oarVerifiTaskDTO);
        return oarVerifiTaskMapper.updateOarVerifiTask(toEntity(oarVerifiTaskDTO));
    }

    /**
     * 提交任务
     * @param oarVerifiTaskDTO
     * @return
     */
    @Override
    public int commitTask(OarVerifiTaskDTO oarVerifiTaskDTO) {
        checkOarVerifiTask(oarVerifiTaskDTO);
        //String userId = SecurityUtils.getLoginUser().getUserId();
        //threadPoolTaskExecutor.execute(() -> {
        //    selectOarVerifiTaskById(oarVerifiTaskDTO.getId()).map(verifiTask -> {
        //        batchInsertOarHouse(verifiTask.getId(), verifiTask.getVerifiDeptId(), userId);
        //        return true;
        //    });
        //});
        return oarVerifiTaskMapper.updateOarVerifiTask(toEntity(oarVerifiTaskDTO));
    }

    /**
     * 批量删除核查任务
     *
     * @param ids 需要删除的核查任务主键
     * @return 结果
     */
    @Override
    public int deleteOarVerifiTaskByIds(String[] ids) {
        return oarVerifiTaskMapper.deleteOarVerifiTaskByIds(ids);
    }

    /**
     * 删除核查任务信息
     *
     * @param id 核查任务主键
     * @return 结果
     */
    @Override
    public int deleteOarVerifiTaskById(String id) {
        return oarVerifiTaskMapper.deleteOarVerifiTaskById(id);
    }

    /*
    统计该批次必填是否已全填
     */
    @Override
    public int countByTaskId(String taskId) {
        return oarVerifiTaskMapper.countByTaskId(taskId);
    }

    /**
     * 统计核查任务数量
     *
     * @param taskState
     * @return
     */
    @Override
    public int countByTaskState(Integer taskState) {
        return oarVerifiTaskMapper.countByTaskState(taskState);
    }

    @Override
    public void batchInsertOarHouse(String taskId, String deptId, String userId) {
        List<OarImpNetHouseDTO> oarImpNetHouseList = oarImpNetHouseService.selectListByTaskId(taskId);
        oarImpNetHouseList.forEach(oarImpNetHouseDTO -> {
            if (1 == oarImpNetHouseDTO.getCheckIsNetHouse()) {
                //房屋
                OarHouseDTO oarHouseDTO = new OarHouseDTO();
                oarHouseDTO.setCompanyName(oarImpNetHouseDTO.getCheckCompanyName());//单位名称
                oarHouseDTO.setBusinessAddr(oarImpNetHouseDTO.getCheckBusinessAddr());//经营地址
                oarHouseDTO.setRoomsNo(oarImpNetHouseDTO.getCheckRoomsNo());//房间数
                oarHouseDTO.setRealTimeState(oarImpNetHouseDTO.getCheckRealTimeState());//场所实时状态
                oarHouseDTO.setTaskSort(0);
                oarHouseDTO.setTaskAuditType(0);
                oarHouseDTO.setCreateBy(userId);
                oarHouseDTO.setDutyPoliceId(userId);
                oarHouseDTO.setDeptId(deptId);
                //SysDept sysDept=sysDeptService.selectDeptById(deptId);
                //if(ToolUtil.isNotEmpty(sysDept)){
                //    oarHouseDTO.setDeptName(sysDept.getDeptName());
                //}
                //从业人员-经营者
                List<OarUserDTO> oarUserList = new ArrayList<>();
                OarUserDTO oarUserDTO = new OarUserDTO();
                oarUserDTO.setDeptId(deptId);
                oarUserDTO.setUserName(oarImpNetHouseDTO.getCheckUserName());
                oarUserDTO.setUserCardType(oarImpNetHouseDTO.getCheckUserCardType());//用户证件类型
                oarUserDTO.setUserCardNo(oarImpNetHouseDTO.getCheckUserCardNo());//用户证件号码
                oarUserDTO.setUserMobile(oarImpNetHouseDTO.getCheckUserMobile());//用户电话
                oarUserDTO.setCreateBy(userId);
                oarUserDTO.setUserType(2);//账号类型  1：房东  2：经营者
                oarUserList.add(oarUserDTO);
                //从业人员-房东
                OarUserDTO oarUserLandlordDTO = new OarUserDTO();
                oarUserLandlordDTO.setDeptId(deptId);
                oarUserLandlordDTO.setUserName(oarImpNetHouseDTO.getCheckLandlordName());
                oarUserLandlordDTO.setUserCardType(oarImpNetHouseDTO.getCheckLandlordCarType());//用户证件类型
                oarUserLandlordDTO.setUserCardNo(oarImpNetHouseDTO.getCheckLandordCardNo());//用户证件号码
                oarUserLandlordDTO.setUserMobile(oarImpNetHouseDTO.getCheckLandordMobile());//用户电话
                oarUserLandlordDTO.setCreateBy(userId);
                oarUserLandlordDTO.setUserType(1);//账号类型  1：房东  2：经营者
                oarUserList.add(oarUserLandlordDTO);

                List<OarRoomsDTO> oarRoomsList = new ArrayList<>();
                if (!ToolUtil.isEmpty(oarImpNetHouseDTO.getCheckRoomsNo())) {
                    for (int i = 0; i < Integer.valueOf(oarImpNetHouseDTO.getCheckRoomsNo()); i++) {
                        OarRoomsDTO oarRoomsDTO = new OarRoomsDTO();
                        oarRoomsList.add(oarRoomsDTO);
                    }
                }
                oarHouseDTO.setOarUserList(oarUserList);
                oarHouseDTO.setOarRoomsList(oarRoomsList);
                oarHouseService.insertOarHouse(oarHouseDTO, 9);
            }
        });
    }

    /**
     * 新增用户
     *
     * @param deptId
     */
    public SysUser insertUser(String userMobile, String deptId) {
        SysUser sysUser = new SysUser();
        //sysUser.setUserId(SnowflakeWorker.nextId());
        //sysUser.setDeptId(deptId);
        //sysUser.setUserType("0");
        //sysUser.setUserName(sysUser.getUserId());
        //sysUser.setPhonenumber(userMobile);
        //sysUser.setStatus("0");
        //sysUser.setDelFlag("0");
        //sysUser.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        //sysUser.setRoleIds(new Long[]{100L});
        //userService.insertUser(sysUser);
        return sysUser;
    }

    /**
     * 校验
     *
     * @param dto
     */
    private void checkOarVerifiTask(OarVerifiTaskDTO dto) {

    }

    private OarVerifiTask toEntity(OarVerifiTaskDTO dto) {
        return BeanUtil.toBean(dto, OarVerifiTask.class);
    }

    private OarVerifiTaskDTO toDto(OarVerifiTask entity) {
        return toDto(entity, false);
    }

    /**
     * 转DTO
     *
     * @param entity
     * @param withDetail 是否查询其他信息
     * @return
     */
    private OarVerifiTaskDTO toDto(OarVerifiTask entity, Boolean withDetail) {
        OarVerifiTaskDTO dto = BeanUtil.toBean(entity, OarVerifiTaskDTO.class);
        if (withDetail) {

        }
        return dto;
    }
}
